package com.suxin.group;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.text.SimpleDateFormat;

/**
 * @Classname NioServerGroupHandler
 * @Description [ TODO ]
 * @Author Tang
 * @Date 2021/1/5 22:02
 * @Created by ASUS
 */
public class NioServerGroupHandler extends SimpleChannelInboundHandler<String> {

    private static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:ss:mm");

    /**
     * handlerAdd 表示连接建立，一旦连接，第一个被执行
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        // 推送给其他客户端
        channels.writeAndFlush("[客户端" + ctx.channel().remoteAddress() + "]加入群聊！\n");
        channels.add(ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        channels.writeAndFlush("[客户端" + ctx.channel().remoteAddress() + "]退出群聊！\n");
        System.out.println("客户端剩余个数：" + channels.size());
    }

    /**
     * 表示 channel 处于活动状态
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress() + " 在线中~");
    }

    /**
     * channel处于不活动状态，提示离线
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress() + " 离线了~");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        Channel channel = ctx.channel();
        System.out.println("服务端转发消息：" + msg);
        channels.forEach(channel1 -> {
            if (channel != channel1) {
                channel1.writeAndFlush("[客户端"+channel.remoteAddress()+"] 发送了消息：" + msg + "\n");
            }else {
                channel.writeAndFlush("[自己]发送了消息：" + msg + "\n");
            }
        });
    }
}